package com.whately.core.base.sms;

import com.github.qcloudsms.SmsMultiSender;
import com.github.qcloudsms.SmsMultiSenderResult;
import com.google.common.collect.Maps;
import com.google.gson.JsonObject;
import com.whately.core.base.utils.GsonUtils;
import com.whately.core.base.utils.http.HttpClientUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;


public class SendSmsUtil {

    private static final Logger log = LoggerFactory.getLogger(SendSmsUtil.class);




        /**
         * 发送短信
         * 注意：内容长度不超过450字，都在会报错
         * 腾讯云
         * @return
         */
        static SmsSendResult sendSingleSms( QcloudSmsInfo qcloudSmsInfo,String mobileOld, String content) {
        //发送结果：result为0标识成功
        SmsSendResult smsSendResult = new SmsSendResult();
        try {
            String result = "";
            //短信内容不能过程，否则发送不去
            if(content.length()>400){
                log.warn("sendSingleSms too long content {}",content);
                content = content.substring(0,400);
            }

            if(StringUtils.isBlank(mobileOld)){
                log.warn("sendSingleSms mobile old is null,mobile old {}",mobileOld);
                smsSendResult.setDescription("手机号码不正确");
                return smsSendResult;
            }

            String[] mobiles = mobileOld.split(",");
            //号码去重
            Set<String> set_mobiles=new HashSet<>();
            for (String mob : mobiles) {
                if(StringUtils.isBlank(mob)){
                    continue;
                }
                set_mobiles.add(mob);
            }

            if(set_mobiles.size()<=0){
                log.warn("sendSingleSms set_mobiles size is zero ,mobile old {}",mobileOld);
                smsSendResult.setDescription("手机号码为空");
                return smsSendResult;
            }

            String phoneNumbers= StringUtils.join(set_mobiles,",");

            String msg = "【"+qcloudSmsInfo.getSmsSign()+"】" +content;
            SmsMultiSender mSender = new SmsMultiSender(qcloudSmsInfo.getQcloudSmsSdkAppId(), qcloudSmsInfo.getQcloudSmsSdkAppKey());
            SmsMultiSenderResult smsMultiSenderResult =  mSender.send(0, "86", phoneNumbers.split(","),msg
                    , "", "");

            if(smsMultiSenderResult!=null){
                result = GsonUtils.toJsonString(smsMultiSenderResult);
            }else{
                log.error("smsMultiSenderResult {} ",result);
            }
            smsSendResult.setDescription(result);
            //转换结果
            if (result !=null ) {
                try{
                    JsonObject jo = GsonUtils.string2JsonObject(result);
                    if(jo!=null&&jo.get("result")!=null&&jo.get("result").getAsInt()==0){
                        smsSendResult.setExecuteResult(true);
                        smsSendResult.setSendStatus(true);
                    }else{
                        log.error("smsMultiSenderResult {} ",result);
                    }
                }catch (Exception e){
                    log.error("sendSingleSms change sms response error ",e);
                }
            }

            return smsSendResult;
        } catch (Exception e) {
            log.error("sendSingleSms error ",e);
            return smsSendResult;
        }

    }

    /**
     * 发送短信
     * 注意：最大402个字或字符
     * 一信通平台
     *威海人社局
     *
     */
    static SmsSendResult sendWhrlzxSms( WhRlzxSmsInfo whRlzxSmsInfo,String mobileOld, String content){
        //发送结果：result为0标识成功
        SmsSendResult smsSendResult = new SmsSendResult();
            //短信内容不能过长，否则发送不去
        if(content.length()>400){
            log.warn("sendWhRlzxSms too long content {}",content);
            content = content.substring(0,400);
        }

        if(StringUtils.isBlank(mobileOld)){
            log.warn("sendWhRlzxSms mobile old is null,mobile old {}",mobileOld);
            smsSendResult.setDescription("手机号码不正确");
            return smsSendResult;
        }

        String[] mobiles = mobileOld.split(",");
        //号码去重
        Set<String> set_mobiles=new HashSet<>();
        for (String mob : mobiles) {
            if(StringUtils.isBlank(mob)){
                continue;
            }
            set_mobiles.add(mob);
        }

        if(set_mobiles.size()<=0){
            log.warn("sendWhrlzxSms set_mobiles size is zero ,mobile old {}",mobileOld);
            smsSendResult.setDescription("手机号码为空");
            return smsSendResult;
        }

        String phoneNumbers= StringUtils.join(set_mobiles,",");

        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        SimpleDateFormat formatTime = new SimpleDateFormat("yyyyMMddHHmmss");

        try{
            Map<String,String> map=  Maps.newHashMap();
            map.put("http.protocol.content-charset","gbk");
            map.put("SpCode", whRlzxSmsInfo.getWhrlzxSmsSdkAppSpCode());
            map.put("LoginName", whRlzxSmsInfo.getWhrlzxSmsSdkAppName());
            map.put("Password", whRlzxSmsInfo.getWhrlzxSmsSdkAppPassword());
            map.put("MessageContent", content);
            map.put("UserNumber",  phoneNumbers);
            map.put("SerialNumber", "000"+format.format(new Date()));
            map.put("ScheduleTime", formatTime.format(new Date()));
            map.put("ExtendAccessNum", "");
            map.put("f", "1");
            String result = HttpClientUtil.doPost(whRlzxSmsInfo.getWhrlzxSmsSdkAppUri(),map,null,"gbk");
            smsSendResult.setDescription(result);

            //转换结果 格式
            //result=33&description=同一号码验证码提交过快
            //result=0&description=发送短信成功&taskid=1171181523881254&faillist=&task_id=1171181523881254
            if (StringUtils.isNotBlank(result) ) {
                try{
                    if(result.contains("result=0")){
                        smsSendResult.setExecuteResult(true);
                        smsSendResult.setSendStatus(true);
                    }else{
                        log.error("sendWhrlzxSms error {} ",result);
                    }
                }catch (Exception e){
                    log.error("sendSingleSms change sms response result {} ,error {}",result,e);
                }
            }

            return smsSendResult;
        }catch (Exception e) {
            log.error("sendWhrlzxSms error {} ",e);
            return smsSendResult;
        }


    }
}
